ema <- function(signal, period){
	#Inicializar el vector todos los elementos en cero
	ema = 0 * signal;
	
	#Armo la constante
	k <- 2 / ( period + 1);
	
	#Genero el EMA
	for(i in 2:length(signal)){
		ema[i] = signal[i] * k + ema[i-1] * (1-k)
	}
	
	ema
}

# Dado un vector que representa un Histograma MACD retorna otro vector de la misma
# cantidad de posiciones. Cada posicion es una posibilidad de operar, si el elemento
# vale 0 no se opera, si el elemento vale 1 indica que es necesario operar. 
getOperations <- function(histogram){
	#creo un vector de la misma cantidad de posiciones, inicializado en cero
	operations <- 0 * histogram;
	for(i in 2:length(histogram)){
		#Si los signos son distintos marco una oportunidad para operar.
		operations[i] = (sign(histogram[i]) != sign(histogram[i-1]));
	}
	operations
}


# Dado un histograma MACD determina si el mercado es propenso a la compra o no
isBearishMarket <- function(histogram, index){
	histogram[index - 1] > histogram[index];
}

# Dado un histograma MACD determina si el mercado es propenso a la venta o no
isBullishMarket <- function(histogram, index){
	histogram[index - 1] < histogram[index];
}

buy <- function (investment, comision, stockPrice){
	#cuantas acciones compro
	stockQty <- floor(investment / ((1+comision)*stockPrice));
	
	stockQty
}

investmentAmount <- function (stockQty, investment, comision, stockPrice){
	#cuanta plata me sobra...
	capital <-(stockQty * stockPrice) * (1+comision); 
	
	capital
}

capitalGain <- function (stockQty, investment, comision, stockPrice){
	#cuanta plata me sobra...
	capital <- (stockQty * stockPrice) * (1-comision); 
	
	capital;
}

simulate <- function(MACDHistogram, stockPrices, capital, comision){
	stocks <- 0;
	operations <- getOperations(MACDHistogram);
	transactionsQty <- 0;
	for(i in 1:length(operations)){
		if(  operations[i] == 1 && stocks == 0 && isBearishMarket(MACDHistogram, i) ){
			#Comprar acciones
			stocks <- buy(capital, comision, stockPrices[i]);
			capital <- capital - investmentAmount(stocks, capital, comision, stockPrices[i]);
			transactionsQty <- transactionsQty + 1;
		}else{
			#Vender acciones
			if( operations[i] == 1 && stocks != 0  && isBullishMarket(MACDHistogram, i) ){
				capital <- capital + capitalGain(stocks, capital, comision, stockPrices[i]);
				stocks <- 0;
				transactionsQty <- transactionsQty + 1;
			}
		}
	}

	#Si me quedan acciones las vendo al ultimo precio conocido
	if(stocks != 0){
		capital <- capital + capitalGain(stocks, capital, comision, stockPrices[length(stockPrices)]);
		transactionsQty <- transactionsQty + 1;
	}
	
	transactions <- list(capital=capital, transactionsQty=transactionsQty);
}

MACDHistogram <- function(closePrices, longPeriod){
	longEMA <- ema(closePrices, longPeriod);
	shortEMA <- ema(closePrices, floor(longPeriod/2));
	macd <- shortEMA - longEMA;
	signal <- ema(macd, 9);
	histogram <- macd - signal;
	
	histogram
}

tsData <- read.csv("table.csv");
closePrices <- tsData$Close;

initialInvestment <- 20000;
periods <- seq(10, 100, 3);
periodsLength <- length(periods);
simulations <- array(rep(0,periodsLength * 5), c(periodsLength, 5));
for(i in 1:periodsLength){
	#Calculo del indicador
	histogram <- MACDHistogram(closePrices, periods[i]);

	#Resultado Acumulado
	aSimulation <- simulate(histogram, closePrices, initialInvestment, 0.015);
 	simulations[i,1] <- periods[i];
	simulations[i,2] <- aSimulation$transactionsQty;
	simulations[i,3] <- aSimulation$capital;
	simulations[i,4] <- aSimulation$capital - initialInvestment;
	simulations[i,5] <- (aSimulation$capital - initialInvestment)/initialInvestment;
}
write.csv(simulations, "simulations.csv");